/**
 * Created by PhpStorm.
 * User: bsc
 * Date: 2020-10-31
 * Time: 22:07
 */
const uploadBtnEl = document.querySelector('.btn')
const fileEl = document.querySelector('#file')
const contentListEl = document.querySelector('.content-list')
const taskPanel = document.querySelector('.task_panel')
const taskBody = document.querySelector('.task_body')

uploadBtnEl.addEventListener('click',()=>{
  fileEl.click();
})

fileEl.onchange = function(){
  // ajax 上传  1.创建->2.open -> 发送 ->接受回调
  let xhr = new XMLHttpRequest();
  xhr.open('post','/upload',true);
  let li = document.createElement('li');
  let span = document.createElement('span');
  let taskProgressStatusdiv = document.createElement('div');
  taskProgressStatusdiv.classList.add('task-progress-status');
  let progressDiv = document.createElement('div');
  progressDiv.classList.add('progress');
  progressDiv.style.width = '0%';
  li.appendChild(span);
  li.appendChild(taskProgressStatusdiv);
  li.appendChild(progressDiv);
  taskBody.appendChild(li);
  xhr.upload.onload = function() {
    taskPanel.style.display = 'none';
  }
  xhr.upload.onloadstart = function() {
    taskPanel.style.display = 'block';
  }
  xhr.upload.onprogress = function(e) {
    taskProgressStatusdiv.innerHTML = (e.loaded / e.total).toFixed(2) + '%';
    progressDiv.style.width = (e.loaded / e.total) + '%';
  }
  xhr.onload = function(){
    let r = JSON.parse(xhr.responseText)
    if(r.state){
      let img = new Image()
      img.src = "/static/upload/"+r.data.name;
      contentListEl.append(img)
    }
  }
  let formData = new FormData();
  formData.append('attachment',fileEl.files[0])
  xhr.send(formData)
}

function getImgList(){
  let xhr = new XMLHttpRequest();
  xhr.open("get",'/getPhotos',true)
  xhr.onload = function(){
    let r = JSON.parse(xhr.responseText);
    for (let i = 0; i < r.data.length; i++) {
      let img = new Image();
      img.src = "/static/upload/"+r.data[i].filename
      contentListEl.append(img)
    }
  }
  xhr.send();
}
getImgList()
